package fr.efrei.tradesys.treatments;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class MailHandler
{

	private static Log	LOGGER	= LogFactory.getLog(MailHandler.class);

	public void sendMail(String mailReceiver, String object, String body)
	{
		LOGGER.info("Sending mail");
		Properties props = new Properties();
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.socketFactory.port", "465");
		props
				.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", "465");
		Session session = Session.getDefaultInstance(props,
				new javax.mail.Authenticator()
				{
					protected PasswordAuthentication getPasswordAuthentication()
					{
						String username = "trading.system.efrei";
						String password = "trading.system.efrei.chatech";
						return new PasswordAuthentication(username, password);
					}
				});
		try
		{
			// Creation of a JavaMail message
			Message mail = new MimeMessage(session);
			// Mail send address
			mail.setFrom(new InternetAddress("trading.system@gmail.com"));
			// Mail receiver address
			mail.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(mailReceiver));
			// Object and body of the mail
			mail.setSubject("[Trading system] " + object);
			mail.setText(body);
			// Mail sending
			Transport.send(mail);
		}
		catch (MessagingException e)
		{
			e.printStackTrace();
		}
	}

}
